#include "rrCintamaniManager.h"
#include "rrCintamaniDOM.h"
#include "rrCintamaniDocument.h"
#include "rrCintamaniUrl.h"
#include "JSObject.h"
#include "variant_list.h"
#include "DOM/Document.h"
#include "global/config.h"
#include "DOM/Window.h"
#include "TINYXML/tinyxml.h"
#include "curl/curl.h"

rrCintamaniManager::rrCintamaniManager( rrCintamaniAPI * api ) : mApi(api)
{
	mWindow = rrCintamaniWindowPtr( new rrCintamaniWindow( mApi->GetHost()->getDOMWindow() ));
	mUrl = mWindow->GetHrefStr();
	// initialize lib curl in main thread.
	curl_global_init(CURL_GLOBAL_ALL);	

}

rrCintamaniManager::~rrCintamaniManager()
{

}

rrCintamaniWindowPtr rrCintamaniManager::GetWindow() const  {
	return mWindow;
}

FB::BrowserHostPtr  rrCintamaniManager::GetHost() const  {
	return mApi->GetHost();
}

std::string rrCintamaniManager::GetDocumentUrl() const 
{ 
	return mUrl;
}


std::string rrCintamaniManager::GetDocumentFolder() const
{
	size_t found;
	found= mUrl.find_last_of("/\\");
	return mUrl.substr(0,found) ; 
}

bool rrCintamaniManager::GetRssFeedList( const std::string & FeedFile, std::vector<OpmlInfo> & feeds )
{
	//Create new document and fill it from a file
	TiXmlDocument * hDoc = new TiXmlDocument();

	if(mWindow->GetProtocolStr().compare("http:")==0){ //location is online
		long returncode;
		rrCintamaniUrl url;
		char * data = url.GetData( GetDocumentFolder(), returncode );//to do
		hDoc->Parse( data );
	}else { // offline
		std::string str = GetDocumentFolder();
		size_t pos = 0;
		pos = str.find("file:///", pos);
		str.replace(pos, 8, "");
		if(!hDoc->LoadFile( str.append("/").append(FeedFile ))) return false;
	}

	// Get opml element.
	TiXmlElement * hRoot = hDoc->RootElement();
	//get body.
	TiXmlElement * hBody= hRoot->FirstChildElement("body");
	//Get the first child <item> element
	TiXmlElement * hNode = hBody->FirstChildElement("outline");
	//Iterate over each <item> element
	while(hNode != 0) {
		OpmlInfo Info;
		Info.text = hNode->Attribute("text") ;
		Info.title = hNode->Attribute("title") ;
		Info.type = hNode->Attribute("type") ;
		Info.xmlUrl = hNode->Attribute("xmlUrl") ;
		Info.htmlUrl = hNode->Attribute("htmlUrl") ;
		hNode = hNode->NextSiblingElement("outline");
		feeds.push_back(Info);
	}

	return true;
}

void rrCintamaniManager::ExtractItem( TiXmlElement* hItem, RssItem& Item ) {

	std::string sBufferK;
	const char * text = 0;
	TiXmlElement * hNode = hItem->FirstChildElement();
	while(hNode != 0) {
		sBufferK = hNode->Value();
		text = hNode->GetText();

		if( text != NULL ) {
			if( sBufferK.compare("title") == 0 ) {
				//mApi->GetHost()->htmlLog("Item ...");
				Item.title = hNode->GetText();  
				//mApi->GetHost()->htmlLog("Item OK");
			}

			if( sBufferK.compare("description") == 0 ) {
				//mApi->GetHost()->htmlLog("description...");
				Item.description = text;//hNode->GetText();
				//mApi->GetHost()->htmlLog("description ok");
			}

			if( sBufferK.compare("link") == 0 ) {
				//mApi->GetHost()->htmlLog("link ...");
				Item.link = hNode->GetText();
				//mApi->GetHost()->htmlLog("link OK");
			}

			if( sBufferK.compare("content:encoded") == 0 ) {
				//mApi->GetHost()->htmlLog("content:encoded ...");
				rrCintamaniElementPtr Encoded = GetWindow()->GetDocument()->CreateElement("content:encoded");
				Encoded->SetInnerHtml( hNode->GetText());

				std::vector<rrCintamaniElementPtr> imgList; 
				Encoded->GetElementsByTagName("img", imgList );

				if(imgList.size()){
					if(imgList[0]->HasAttribute("src")) {
						rrCintamaniImage * Image = new rrCintamaniImage();
						Image->src = imgList[0]->GetAttribute("src");
						if(imgList[0]->HasAttribute("alt"))
						Image->alt = imgList[0]->GetAttribute("alt");
						Item.img = Image;
					}
					else
					{
						//mWindow->Alert( "No SRC Attribute ");
					}
				}
			}
		}

		hNode = hNode->NextSiblingElement();
	}
}  

bool rrCintamaniManager::GetRssFeed( const std::string & UrlFeed, std::vector<RssItem>& res )
{
	long returncode;
	rrCintamaniUrl url;
	char * data = url.GetData( UrlFeed, returncode );

	std::ostringstream CountStr;
	CountStr << returncode ;
	//GetWindow()->Alert( CountStr.str()  );

	if( returncode == 200 ) { // 301 

		//Create new document and fill it from a file
		TiXmlDocument * hDoc = new TiXmlDocument();
		// parse data.
		hDoc->Parse( data );
		// Get Root element // rss
		TiXmlElement * hRoot= hDoc->RootElement();
		if(!hRoot){ /* GetWindow()->Alert( "No Root Item" ); */ return false; }

		const char * Version = hRoot->Attribute("version");
		//get channel.
		TiXmlElement * hChannel= hRoot->FirstChildElement();
		if(!hChannel){ /*GetWindow()->Alert( "No Channel" ); */ return false; }

		//Get the first child <item> element
		TiXmlElement * hNode = hChannel->FirstChildElement("item");
		if(!hNode){ /* GetWindow()->Alert( "No Item !" );*/ return false; }
		//Iterate over each <item> element
		while(hNode != 0) {
			//if(UrlFeed.compare("http://blog.casa.ucl.ac.uk/?feed=rss2") == 0) {
				RssItem Item;
				ExtractItem(hNode, Item );
				res.push_back(Item );
			//}
			hNode = hNode->NextSiblingElement("item");
		}
	}
	else {
		// error code
		return false;
	}

}

void rrCintamaniManager::AddPanel( Panel * pan )
{
	mPanels.push_back(pan);
	//pan->AddListener(this);
}
 